/** IT后备电池面板部件
* Author:      yangjq
* CreateTime:  2023/9/6 10:17:38
* LastEditor:  yangjq
* ModifyTime:  2023/12/5 20:36:00
* Description:
*/
<template>
  <div :style="{width:props.width , height:props.height,display: 'flex', flexDirection: 'column', color: 'whitesmoke'}">
    <div ref="echartRefH" style="height: 2%; width: 100%;text-align:center;padding: 12px 0px 4px 0px;">
      <span class="ups-header">{{ upsTitle }}</span>
    </div>
    <div class="ups-V" style="height: 35%; width: 100%">
      <div ref="echartRefV" style="height: 100%; width: 100%"></div>
    </div>
    <div class="ups-I" style="height: 31.5%; width: 100%">
      <div ref="echartRefI" style="height: 100%; width: 100%"></div>
    </div>
    <div class="ups-B" style="height: 31.5%; width: 100%;display: flex;">
      <div ref="echartRefB" style="height: 100%; width: 70%"></div>
      <div style="height:100%;display: flex;flex-direction: column;justify-content: center;">
        <div style="font-size: 20px">电池后备时间</div>
        <div style="font-size: 24px;margin: 0 auto">{{ batteryTime }}</div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, Ref, reactive, watchEffect, onBeforeMount, onMounted, watch, nextTick} from 'vue';
import {useECharts} from '/@/hooks/web/useECharts';
import {defHttp} from "/@/utils/http/axios";

const props = defineProps({
  width: {type: String, default: '100%'},
  height: {type: String, default: '100%'},
  roomIndex: {type: Number, default: 0}
});
const echartRefV = ref<HTMLDivElement | null>(null);
const echartRefI = ref<HTMLDivElement | null>(null);
const echartRefB = ref<HTMLDivElement | null>(null);

const {
  setOptions: setBOptions,
  echarts,
  getInstance: chartInstance
} = useECharts(echartRefB as Ref<HTMLDivElement>, 'dark');
const {
  setOptions: setVOptions,
  echarts: echartsV,
  getInstance: chartInstanceV
} = useECharts(echartRefV as Ref<HTMLDivElement>, 'dark');
const {
  setOptions: setIOptions,
  echarts: echartsI,
  getInstance: chartInstanceI
} = useECharts(echartRefI as Ref<HTMLDivElement>, 'dark');
const optionV = reactive({});
const optionI = reactive({});
const optionB = reactive({});
const upsTitle = ref('1号UPS-参数');
let upsIndex = 0;
const UPS_TITLES = ['1号UPS-参数', '2号UPS-参数', '3号UPS-参数', '4号UPS-参数'];
const UPS_NAMES = ['艾默生UPS1', '艾默生UPS2', '艾默生UPS3', '艾默生UPS4'];

//柱条的颜色，每个柱条颜色不同
const upsColor = ["#FF3300", "#0066FF", "#FF9900", "#33FF00", "#33FFFF", "#FFFF00", "#9999FF"];

const dataList = ref([
  {
    value: 23,
  },
  {
    value: 52,
  },
  {
    value: 32,
  }
]);

function initBCharts() {
  Object.assign(
    optionB,
    reactive({
      tooltip: {
        formatter: '{b} : {c}%'
      },
      title: {
        text: "负载率",
        textVerticalAlign: 'top',
        left: 'center',
        top: 0,
        textStyle: {
          color: '#fff',
          textBorderWidth: '1',
          width: '100%',
          fontWeight: '400'
        }
      },
      //backgroundColor:'rgba(128, 128, 128, 0.1)', //rgba设置透明度0.1
      animationEasing: 'elasticOut',
      animationDelayUpdate: function (idx) {
        return idx * 10;
      },
      grid: {left: 22, top: 24, right: 22, bottom: 0, containLabel: true},
      yAxis: [
        {
          type: 'category',
          data: [
            {
              value: "A相负载",
            },
            {
              value: "B相负载",
            },
            {
              value: "C相负载",
            }
          ],
          inverse: true,//数组翻转显示
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          nameTextStyle: {
            fontWeight: 700,
            fontSize: 12,
            color: '#ffffff'
          },
          axisLabel: {
            textStyle: {
              color: '#ffffff',
            },
          },
          // splitLine:{show: false},
          // splitArea:{
          //   show: true,
          // },
        },
      ],
      xAxis: {
        type: 'value',
        splitLine: {show: false},
        show: false,
        min: 0,
        max: 100,
      },
      series: [
        {
          type: 'bar',
          data: dataList,
          barGap: '20%',
          barCategoryGap: '40%',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(220, 220, 220, 0.1)',
            borderRadius: 16
          },
          label: {
            show: true,
            position: 'inside',
            color: '#fff',
            fontSize: 12,
            formatter: '{c}%',
          },
          itemStyle: {
            borderRadius: 16,//圆角
            color: function (params) {
              return upsColor[params.dataIndex]
            }
          },
          emphasis: {
            focus: 'series',
            blurScope: 'coordinateSystem'
          },
          // showBackground: true,
          animationDurationUpdate: 1000, // 更新动画时长为 1s
          animationEasingUpdate: 'quinticInOut', // 更新动画缓动效果为 'quinticInOut'
          animationDelay: function (idx) {
            return idx * 10 + 100;
          }
        },
      ]
    })
  );
  setBOptions(optionB);
}

function initVCharts() {
  Object.assign(
    optionV,
    reactive({
      tooltip: {
        formatter: '{b} : {c}V'
      },
      // grid: { left: 20, top: 10, right: 20, bottom: 10,containLabel:true },
      series: [
        {
          type: 'gauge',
          name: '主入Ua',
          startAngle: 225,
          endAngle: -45,
          center: ['18%', '57%'],
          radius: '75%',//80
          max: 300,
          min: 0,
          axisLine: {
            lineStyle: {
              width: 2,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          itemStyle: {
            color: upsColor[0],
          },
          progress: {
            show: true,
            color: upsColor[0],
            width: 3,
          },
          pointer: {
            itemStyle: {
              color: upsColor[0],
            }
          },
          axisTick: {
            distance: 4,
            length: 4,
            lineStyle: {
              color: 'auto',
              width: 1
            }
          },
          splitLine: {
            distance: 4,
            length: 8,
            lineStyle: {
              color: 'auto',
              width: 2
            }
          },
          title: {
            fontSize: 17,
            fontWeight: 'bold',
            color: upsColor[0],
            offsetCenter: [0, '80%']
          },
          axisLabel: {
            color: 'inherit',
            distance: 10,
            fontSize: 8
          },
          detail: {
            valueAnimation: true,
            formatter: '{value} V',
            color: upsColor[0],
            fontSize: 18,
            offsetCenter: [0, '40%']
          },
          data: [
            {
              value: termVoltageA.value,
              name: '主入Ua'
            }
          ]
        },
        {
          type: 'gauge',
          name: '主入Ub',
          startAngle: 225,
          endAngle: -45,
          center: ['50%', '57%'],
          radius: '75%',
          max: 300,
          min: 0,
          axisLine: {
            lineStyle: {
              width: 2,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          itemStyle: {
            color: upsColor[1],
          },
          progress: {
            show: true,
            color: upsColor[1],
            width: 3,
          },
          pointer: {
            itemStyle: {
              color: upsColor[1],
            }
          },
          axisTick: {
            distance: 4,
            length: 4,
            lineStyle: {
              color: 'auto',
              width: 1
            }
          },
          splitLine: {
            distance: 4,
            length: 8,
            lineStyle: {
              color: 'auto',
              width: 2
            }
          },
          title: {
            fontSize: 17,
            fontWeight: 'bold',
            color: upsColor[1],
            offsetCenter: [0, '80%']
          },
          axisLabel: {
            color: 'inherit',
            distance: 10,
            fontSize: 8
          },
          detail: {
            valueAnimation: true,
            formatter: '{value} V',
            color: upsColor[1],
            fontSize: 18,
            offsetCenter: [0, '40%']
          },
          data: [
            {
              value: termVoltageB.value,
              name: '主入Ub'
            }
          ]
        },
        {
          type: 'gauge',
          name: '主入Uc',
          startAngle: 225,
          endAngle: -45,
          center: ['82%', '57%'],
          radius: '75%',
          max: 300,
          min: 0,
          axisLine: {
            lineStyle: {
              width: 2,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          itemStyle: {
            color: upsColor[2],
          },
          progress: {
            show: true,
            color: upsColor[2],
            width: 3,
          },
          pointer: {
            itemStyle: {
              color: upsColor[2],
            }
          },
          axisTick: {
            distance: 4,
            length: 4,
            lineStyle: {
              color: 'auto',
              width: 1
            }
          },
          splitLine: {
            distance: 4,
            length: 8,
            lineStyle: {
              color: 'auto',
              width: 2
            }
          },
          title: {
            fontSize: 17,
            fontWeight: 'bold',
            color: upsColor[2],
            offsetCenter: [0, '80%']
          },
          axisLabel: {
            color: 'inherit',
            distance: 10,
            fontSize: 8
          },
          detail: {
            valueAnimation: true,
            formatter: '{value} V',
            color: upsColor[2],
            fontSize: 18,
            offsetCenter: [0, '40%']
          },
          data: [
            {
              value: termVoltageC.value,
              name: '主入Uc'
            }
          ]
        }
      ]
    })
  );
  setVOptions(optionV);
}

function initICharts() {
  Object.assign(
    optionI,
    reactive({
      title: {
        // text: 'title',
        left: 'center',
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        borderWidth: 1,
        textStyle: {
          color: 'rgba(0, 0, 0, 0.7)',
          fontSize: 12,
        },
        // 坐标轴指示器，坐标轴触发有效
        axisPointer: {
          type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
        },
      },
      axisPointer: {
        snap: true,
        label: {
          backgroundColor: '#777',
        },
      },
      grid: {top: 'center', left: 'center',width:'82%', height: '80%', containLabel: true},
      xAxis: {
        type: 'category',
        name: '',
        show: true,
        nameLocation: 'end',
        nameTextStyle: {
          fontWeight: 700,
          fontSize: 12,
          color: '#ffffff'
        },
        axisLabel: {
          textStyle: {
            color: '#ffffff',
          },
        },
        axisLine: {
          show: true,
        },
        boundaryGap: true,
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        name: '电流(A)',
        nameLocation: 'center',
        nameGap: 35,
        nameRotate: 90,
        nameTextStyle: {
          fontWeight: 700,
          fontSize: 12,
          color: '#ffffff'
        },
        axisLabel: {
          textStyle: {
            fontSize: 12,
            color: '#ffffff',
          },
        },

        //坐标线
        axisLine: {
          show: false,
        },
        axisTick: false,
        splitLine: {show: false},
        splitArea: {
          show: true,
          areaStyle: {
            color: ['rgba(250,250,250,0)', 'rgba(200,200,200,0.1)'],
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
      series: [
        {
          type: 'bar',
          data: [
            ['输出电流A', outputCurrentA.value],
            ['输出电流B', outputCurrentB.value],
            ['输出电流C', outputCurrentC.value],
          ],
          name: 'UPS',
          // id: "0",
          barGap: '0%',
          barMaxWidth: 30,
          label:{
              show:true,
              color:'#fff',
              position: "outside",
              fontSize: 12,
            },
          colorBy: "data",
          itemStyle: {
            normal: {
              //这里是颜色
              color: function (params) {
                //注意，如果颜色太少的话，后面颜色不会自动循环，最好多定义几个颜色
                //var colorList = ['#00A3E0', '#FFA100', '#ffc0cb', '#CCCCCC', '#BBFFAA', '#749f83', '#ca8622'];
                return upsColor[params.dataIndex];
              },
            },
          },
        },
      ],
    })
  );
  setIOptions(optionI);
}

const termVoltageA = ref(100);
const termVoltageB = ref(200);
const termVoltageC = ref(180);
const outputCurrentA = ref(110);
const outputCurrentB = ref(110);
const outputCurrentC = ref(98.5);
const loadA = ref(0);
const loadB = ref(0);
const loadC = ref(0);
const batteryTime = ref(80)

function loadData(name) {

  let api = "/screen/it/upsRoomInfo";
  let params = {};
  let options = {isTransformResponse: false};
  defHttp.get({url: api, params}, options)
    .then((res) => {
      if (res.success) {
        res.result.forEach(function (element) {
          if (element.name === name) {
            termVoltageA.value = element.termVoltageA
            termVoltageB.value = element.termVoltageB
            termVoltageC.value = element.termVoltageC
            outputCurrentA.value = element.outputCurrentA
            outputCurrentB.value = element.outputCurrentB
            outputCurrentC.value = element.outputCurrentC
            loadA.value = element.loadA
            loadB.value = element.loadB
            loadC.value = element.loadC
            batteryTime.value = element.batteryTime
          }
        });
      } else {
        console.log('接口错误用默认');
      }
    })
    .finally(() => {
      reloadData()
    });
}

/**
 * 重新加载数据
 * */
const reloadData = () => {
  upsIndex++;
  if (upsIndex >= UPS_TITLES.length) {
    upsIndex = 0;
  }
  upsTitle.value = UPS_TITLES[upsIndex];

  dataList.value = [loadA.value, loadB.value, loadC.value]

  initVCharts();

  initICharts();

  initBCharts();  
};
onMounted(() => {
  initBCharts();//负载
  initVCharts();//电压
  initICharts();//电流

  loadData("艾默生UPS1");

  // for (var i=0;i<UPS_NAMES.length;i++) {

  // if (i===UPS_NAMES.length-1){
  //   i=0;
  // }
  // }

  // setInterval(()=>{
  //   reloadData();
  // },60000);
  startSetInterval();
});

/**
 * 监听roomIndex变化
 */
// watch(
//   () => props.roomIndex,
//   () => {
//     console.log(props.roomIndex)
//     loadData(UPS_NAMES[props.roomIndex])
//   },
//   {
//     immediate: true,
//   }
// );

let timer1;
let dataKey = 0;

watchEffect(() => {
  // if (timer1 != null) {
  //   clearInterval(timer1)
  // }
});


function startSetInterval() {

  timer1 = setInterval(function () {

    if (dataKey > UPS_NAMES.length-1 ) {
      dataKey = 0;
    }
    loadData(UPS_NAMES[dataKey])
    dataKey++;
  }, 30000);

}


</script>

<style scoped lang="less">
.ups-header {
  font-size: 1.3rem;
  color: #fff;
  font-weight: 500;
}
</style>
